<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UploadFilled, Download, FolderAdd, Delete, Search } from '@element-plus/icons-vue'
import { useFileStore } from '@/stores/file'
import axios from 'axios'
// 设置axios基础URL
axios.defaults.baseURL = 'http://localhost:5177'
// 文件列表数据
const fileList = ref([])
const files = ref([])
const folderList = ref([])
const currentFolderId = ref('root') // 当前文件夹ID，根目录为'root'
const useStore = useFileStore()
const uploadRef = ref() // 上传组件引用
// 上传状态
const uploading = ref(false);
// 文件夹创建 - 暂未使用但保留
// const newFolderName = ref('')
// const showNewFolderDialog = ref(false)

// 文件搜索
const searchKeyword = ref('')

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 获取文件列表
const fetchFileList = async () => {
  try {
    // 调用API获取分页文件列表
    const response = await useStore.getfiles({
      page: currentPage.value,
      size: pageSize.value,
      keyword: searchKeyword.value
    });
    console.log(response.files)
    fileList.value = response.files
    total.value = response.total || 0
    console.log(response);
  } catch (error) {
    ElMessage.error('获取文件列表失败')
    console.error(error)
  }
}
const handleFileChange = (uploadFile) => {
  const file = uploadFile.raw
  const isLessThan10MB = file.size / 1024 / 1024 < 10
  const allowedTypes = [
    // 图片类型
    'image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/bmp', 'image/webp', 'image/svg+xml',
    // 文档类型
    'application/pdf',
    'application/msword', // .doc
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document', // .docx
    'application/vnd.ms-excel', // .xls
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // .xlsx
    'application/vnd.ms-powerpoint', // .ppt
    'application/vnd.openxmlformats-officedocument.presentationml.presentation', // .pptx
    // 文本类型
    'text/plain', // .txt
    'text/markdown', // .md
    'text/x-markdown', // .md (alternative)
    'text/csv', // .csv
    'application/json', // .json
    'application/xml', // .xml
    'text/xml', // .xml
    'text/html', // .html
    'text/css', // .css
    'application/javascript', // .js
    'text/javascript', // .js
    // 压缩文件类型
    'application/zip', // .zip
    'application/x-zip-compressed', // .zip (alternative)
    'application/x-rar-compressed', // .rar
    'application/x-7z-compressed', // .7z
    'application/x-tar', // .tar
    'application/gzip', // .gz
    'application/x-gzip', // .gz (alternative)
    // 音频类型
    'audio/mpeg', // .mp3
    'audio/wav', // .wav
    'audio/ogg', // .ogg
    // 视频类型
    'video/mp4', // .mp4
    'video/avi', // .avi
    'video/x-msvideo', // .avi (alternative)
    'video/quicktime', // .mov
    // 其他常用类型
    'application/octet-stream' // 通用二进制文件
  ]
  const isAllowedType = allowedTypes.includes(file.type)

  if (!isLessThan10MB) {
    ElMessage.error('文件大小不能超过10MB！')
    return
  }
  if (!isAllowedType) {
    ElMessage.error('不支持的文件类型！')
    return
  }

  files.value.push(file) // ✅ 合法文件才 push

  ElMessage.success(`文件 ${file.name} 已选择，等待上传`)
}

// 处理文件移除
const handleFileRemove = (uploadFile) => {
  const index = files.value.findIndex(file => file.name === uploadFile.name && file.size === uploadFile.size)
  if (index > -1) {
    files.value.splice(index, 1)
  }
}


/**
 * 手动上传文件到服务器
 */
// const uploadFiles = async () => {
//   if (fileList.value.length === 0) {
//     ElMessage.warning('请先选择文件！');
//     return;
//   }
//   console.log(1111);

//   uploading.value = true;

//   try {
//     // 1. 创建 FormData 对象
//     const formData = new FormData();

//     // 2. 将所有文件添加到 FormData (字段名必须与后端一致)
//     // 注意: 根据错误信息，后端期望的字段名是 'file' (不是 'files')
//     fileList.value.forEach((file) => {
//       formData.append('file', file); // 关键: 使用 'file' 作为字段名
//     });

//     // 3. 发送请求 (替换为你的实际 API 地址)
//     // 注意: 这里假设 useStore.uploadfiles 是封装好的上传方法
//     // 如果没有封装，可以直接用 axios:
//     /*
//     const response = await axios.post('/api/files/upload', formData, {
//       headers: {
//         'Authorization': `Bearer ${token.value}`,
//         // 不要手动设置 Content-Type，让浏览器自动处理 multipart/form-data
//       }
//     });
//     */
//     console.log('准备发送请求...', formData);
//     // const response = await axios.post('/api/files/upload',formData,{
//     //   headers:{
//     //     'Authorization':`Bearer ${useStore.token}`
//     //   }
//     // }) // 假设 useStore 已正确实现
//     const response = await useStore.uploadfiles(formData); // 假设 useStore 已正确实现
//     // 4. 上传成功处理
//     ElMessage.success('文件上传成功！');
//     fetchFileList()
//     // 5. 清空文件列表
//     // fileList.value = [];//
//   } catch (error) {
//     if (error.response) {
//       // 服务器返回了响应，但状态码是 4xx/5xx
//       console.error('上传失败详情:', {
//         status: error.response.status,
//         data: error.response.data,
//         headers: error.response.headers
//       });
//       ElMessage.error('上传失败: ' + (error.response.data?.message || '服务器错误'));
//     } else if (error.request) {
//       // 请求已发出，但没有收到响应（网络错误、跨域问题等）
//       console.error('无响应详情:', {
//         request: error.request
//       });
//       ElMessage.error('网络错误，请检查连接或跨域设置');
//     } else {
//       // 其他错误（如代码逻辑错误）
//       console.error('未知错误:', error.message);
//       ElMessage.error('上传失败: ' + error.message);
//     }
//   } finally {
//     uploading.value = false;
//   }
// };

const uploadFiles = async () => {
  if (!files.value.length) return ElMessage.warning('请先选择文件')

  uploading.value = true
  const form = new FormData()
  files.value.forEach(f => form.append('file', f))

  try {
    await axios.post('/api/file/upload', form, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`
      }
    })
    ElMessage.success('上传成功')

    //立即刷新列表
    await fetchFileList()

    // 清空文件数组和上传组件
    files.value = []
    uploadRef.value?.clearFiles() // 清空上传组件中的文件列表
  } catch (e) {
    ElMessage.error(e.response?.data?.message || '上传失败')
  } finally {
    uploading.value = false
  }
}


//格式化时间
const formatDate = (time) => {
  if (!time) return '';
  const date = new Date(time);
  const beijingTime = new Date(date.getTime() + 8 * 3600 * 1000); // 转换为北京时间
  return beijingTime.toISOString().replace('T', ' ').substring(0, 19); // 格式化为 YYYY-MM-DD HH:MM:SS
};

// 删除文件

const confirmDelete = (fileId) => {
  ElMessageBox.confirm(
    '确定要删除此文件吗？此操作不可恢复。',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    handleDelete(fileId); // 调用实际删除方法
  }).catch(() => {
    // 用户取消删除
  });
};
const handleDelete = async (fileId) => {
  try {
    // 调用删除API
    await useStore.deleteFile(fileId);

    ElMessage.success('文件删除成功！');

    // 可选：刷新文件列表（如果你的页面有文件列表）
    fetchFileList(); // 假设这是你的刷新方法
  } catch (error) {
    ElMessage.error('文件删除失败: ' + error.message);
  }
};
const downloading = ref(false);

// 下载文件
const handleDownload = async (fileId, fileName) => {
  try {
    downloading.value = true;

    const response = await axios.get(`/api/file/${fileId}/download-file`, {
      responseType: 'blob',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });

    // 使用传入的文件名或从响应头获取
    let downloadFileName = fileName || `file_${fileId}`;

    const disposition = response.headers['content-disposition'];
    if (disposition) {
      const match = disposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
      if (match && match[1]) {
        downloadFileName = match[1].replace(/['"]/g, '');
      }
    }

    // 创建下载链接
    const url = window.URL.createObjectURL(response.data);
    const link = document.createElement('a');
    link.href = url;
    link.download = downloadFileName;
    document.body.appendChild(link);
    link.click();

    // 清理
    setTimeout(() => {
      window.URL.revokeObjectURL(url);
      document.body.removeChild(link);
    }, 100);

    ElMessage.success('文件下载成功！');
  } catch (error) {
    console.error('下载错误:', error);

    // 友好的错误提示
    if (error.response?.status === 404) {
      ElMessage.error('下载失败，文件不存在');
    } else if (error.response?.status === 403) {
      ElMessage.error('下载失败，没有权限访问该文件');
    } else if (error.response?.status === 401) {
      ElMessage.error('下载失败，请先登录');
    } else if (error.response?.status >= 500) {
      ElMessage.error('下载失败，服务器内部错误');
    } else if (error.response?.data?.message) {
      ElMessage.error(`下载失败：${error.response.data.message}`);
    } else if (error.code === 'NETWORK_ERROR' || !error.response) {
      ElMessage.error('下载失败，网络连接错误');
    } else {
      ElMessage.error('下载失败，请稍后重试');
    }
  } finally {
    downloading.value = false;
  }
}
// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 搜索文件
const searchFiles = () => {
  currentPage.value = 1 // 搜索时重置到第一页
  fetchFileList()
}

// 分页处理
const handlePageChange = (page) => {
  currentPage.value = page
  fetchFileList()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1 // 改变页面大小时重置到第一页
  fetchFileList()
}

// 进入文件夹
const enterFolder = (folder) => {
  currentFolderId.value = folder.id
  fetchFileList()
}

onMounted(() => {
  fetchFileList()
})
</script>

<template>
  <div class="file-management-system">
    <el-card class="main-card">
      <template #header>
        <div class="card-header">
          <h2>文件管理系统</h2>
          <div class="header-actions">
            <el-input v-model="searchKeyword" placeholder="搜索文件..." prefix-icon="Search" clearable @clear="searchFiles"
              @keyup.enter="searchFiles" class="search-input" />
            <el-button type="primary" :icon="Search" @click="searchFiles">搜索</el-button>
          </div>
        </div>
      </template>

      <!-- 面包屑导航 -->
      <!-- <el-breadcrumb separator="/" class="breadcrumb">
        <el-breadcrumb-item @click="currentFolderId = 'root'; fetchFileList()">根目录</el-breadcrumb-item>
        <el-breadcrumb-item 
          v-for="folder in getFolderPath(currentFolderId)" 
          :key="folder.id"
          @click="currentFolderId = folder.id; fetchFileList()"
        >
          {{ folder.name }}
        </el-breadcrumb-item>
      </el-breadcrumb> -->

      <!-- 文件夹操作 -->
      <!-- <div class="folder-actions">
        <el-button type="primary" :icon="FolderAdd" @click="showNewFolderDialog = true">
          创建文件夹
        </el-button>
      </div>

      // 新建文件夹对话框 
      <el-dialog v-model="showNewFolderDialog" title="创建文件夹" width="30%">
        <el-input v-model="newFolderName" placeholder="请输入文件夹名称" />
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="showNewFolderDialog = false">取消</el-button>
            <el-button type="primary" @click="handleCreateFolder">确认</el-button>
          </span>
        </template>
      </el-dialog> -->

      <!-- 文件上传 -->
      <div class="upload-area">
        <!-- <el-upload class="upload-component" drag :auto-upload="false" :on-change="handleFileChange"
          :show-file-list="false" multiple
          accept=".jpg,.jpeg,.png,.gif,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.zip,.rar"
          :http-request="uploadFiles">
          <el-icon class="el-icon--upload">
            <UploadFilled />
          </el-icon>
          <div class="el-upload__text">
            拖拽文件到此处或 <em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              支持多文件上传，文件大小不超过5MB，仅支持特定文件格式
            </div>
          </template>
        </el-upload>
        <el-button type="primary" @click="uploadFiles" :loading="uploading" :disabled="fileList.length === 0">
          {{ uploading ? "上传中..." : "开始上传" }}
        </el-button> -->
        <el-upload ref="uploadRef" drag multiple :auto-upload="false" :on-change="handleFileChange"
          :on-remove="handleFileRemove" :show-file-list="true"
          accept=".jpg,.jpeg,.png,.gif,.bmp,.webp,.svg,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.md,.csv,.json,.xml,.html,.css,.js,.zip,.rar,.7z,.tar,.gz,.mp3,.wav,.ogg,.mp4,.avi,.mov">
          <el-icon>
            <UploadFilled />
          </el-icon>
          <div>拖拽或点击选择文件</div>
          <template #tip>
            <div class="el-upload__tip">
              支持图片、文档(Word/Excel/PPT)、文本(TXT/MD)、压缩包、音视频等多种格式，文件大小不超过10MB
            </div>
          </template>
        </el-upload>

        <el-button type="primary" @click="uploadFiles" :loading="uploading" :disabled="!files.length">
          {{ uploading ? '上传中...' : '开始上传' }}
        </el-button>
      </div>
      <!-- 可选：显示已选择的文件列表 -->
      <!-- <div v-if="fileList.length > 0" class="selected-files">
            <div v-for="(file, index) in fileList" :key="index" class="file-item">
              <span>{{ file.name }}</span>
              <el-button @click="removeFile(index)" size="small" type="danger">删除</el-button>
            </div>
          </div> -->

      <!-- 上传按钮 -->


      <!-- 上传进度 -->
      <div v-if="uploading" class="upload-progress">
        <div class="progress-info">
          <span>文件上传中...</span>
        </div>
        <el-progress :percentage="100" status="success" />
      </div>

      <!-- 文件列表 -->
      <div v-if="fileList.length || folderList.length" class="file-list-container">
        <!-- 文件夹列表 -->
        <div v-if="folderList.length" class="folder-list">
          <h3>文件夹</h3>
          <el-table :data="folderList" style="width: 100%" size="small">
            <el-table-column prop="name" label="文件夹名称" />
            <el-table-column prop="createTime" label="创建时间" width="180" />
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-button link type="primary" :icon="Download" @click="enterFolder(scope.row)">
                  进入
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 文件列表 -->
        <div class="file-list">
          <h3>文件列表</h3>
          <el-table :data="fileList" style="width: 100%" size="small">
            <el-table-column prop="id" label="文件Id" show-overflow-tooltip />
            <el-table-column prop="originalName" label="文件名称" min-width="200" show-overflow-tooltip />
            <el-table-column prop="mimeType" label="文件类型" width="120" />
            <el-table-column prop="size" label="文件大小" width="120">
              <template #default="{ row }">
                {{ formatFileSize(row.size) }} <!-- 新增格式化方法 -->
              </template>
            </el-table-column>
            <el-table-column label="上传时间" width="160">
              <template #default="{ row }">
                {{ formatDate(row.createdAt) }}
              </template>
            </el-table-column>
            <el-table-column prop="username" label="上传者" width="120" />
            <el-table-column label="操作" width="200">
              <template #default="{ row }">
                <el-button link type="primary" :icon="Download" @click="handleDownload(row.id, row.originalName)">
                  下载
                </el-button>
                <el-button link type="danger" :icon="Delete" @click="confirmDelete(row.id)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页组件 -->
          <div class="pagination-container">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]" :total="total" layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange" @current-change="handlePageChange" />
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-else class="empty-state">
        <el-empty description="暂无文件或文件夹" />
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.file-management-system {
  padding: 20px;
}

.main-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.search-input {
  width: 250px;
}

.breadcrumb {
  margin-bottom: 20px;
}

.folder-actions {
  margin-bottom: 20px;
}

.upload-area {
  margin-bottom: 20px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  transition: border-color 0.3s;
}

.upload-area:hover {
  border-color: #409EFF;
}

.upload-component {
  width: 100%;
}

.upload-area {
  margin: 20px 0;
}

.selected-files {
  margin: 10px 0;
}

.file-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 0;
  border-bottom: 1px solid #eee;
}

.upload-progress {
  margin-bottom: 20px;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.file-list-container {
  margin-top: 20px;
}

.folder-list,
.file-list {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.empty-state {
  margin-top: 50px;
  text-align: center;
}
</style>